package com.zhentao.controller;

import com.zhentao.bean.Result;
import com.zhentao.pojo.Users;
import com.zhentao.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    //检查用户名是否已存在
    @RequestMapping("/user/checkUsernameHad")
    @ResponseBody
    public Result checkUsernameHad(String username){
        //调用业务层，查询当前用户名是否已存在
        Users byName = userService.findByName(username);
        if(byName!=null){
            return Result.Ok("用户名已存在");
        }else{
            return Result.ERROR("用户名不存在");
        }
    }
    @RequestMapping("user/register")
    @ResponseBody
    public Result register(Users users,String upass){
        //必须后台还得校检
        String username=users.getUsername();
        if(username ==null || username.length()==0){
            return Result.ERROR(40001,"用户名不能为空",null);
        }
        String password= users.getPassword();
        if(password==null || password.length()==0){
            return Result.ERROR(40002,"密码不能空",null);
        }
        if(!password.equals(upass)){
            return Result.ERROR(40003,"两次密码不一致",null);
        }
        Users userByUsername = userService.findByName(username);
        if(userByUsername != null){
            return Result.ERROR("用户名已经存在");
        }
        //注册
        userService.save(users);
        return Result.Ok();

    }
    //登录
    @RequestMapping("/user/login")
    @ResponseBody
    public Result login(String username, String password, HttpSession session){
        //调用业务层实现用户名和密码的验证
        Users byName = userService.findByName(username);
        //如果验证失败---前段提示
        if(byName==null){
            return Result.ERROR("用户名或密码有误");
        }
        if (!byName.getPassword().equals(password)){
            return Result.ERROR("登陆成功");
        }

        //验证成功--给前段提示，跳转主页，巴登录用户信息存入session
        session.setAttribute("username",username);
        return Result.Ok();
    }
}
